import db from "@/server/connector/db";
import userJwtService from "@/server/service/user-jwt-service";
import _ from "lodash";
import { CookieNames } from "@/shared/cookies";
import cookieService from "@/server/service/cookie-service";
import { User } from "@prisma/client";
import AppError from "@/shared/app-error";

async function getFromRequest(req: Request): Promise<User | null> {
  return await getFromHeaders(req.headers);
}

async function getFromHeaders(headers: Headers): Promise<User | null> {
  const cookies = cookieService.getCookies(headers);
  const jwt = cookies[CookieNames.TOKEN];

  if (jwt) {
    const result = await userJwtService.verifyJwt(jwt);
    if (result.ok) {
      const { userId } = result;
      return await db.user.findUnique({ where: { id: userId } });
    }
  }
  throw AppError.unauthError();
}

const loginUserService = {
  getFromHeaders,
  getFromRequest,
};

export default loginUserService;
